package com.example.myapplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DatabaseActivity extends AppCompatActivity {
    private DBHelper dbHelper;
    private SQLiteDatabase db;
    private EditText name,age;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_database);
        aaa(this, 0);
        dbHelper = new DBHelper(this, "test.db");
        db = dbHelper.getWritableDatabase();
        name = findViewById(R.id.et_name);
        age = findViewById(R.id.et_age);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }
    private void aaa(Activity activity, int curImg) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Toast.makeText(activity, "请打开存储权限", Toast.LENGTH_SHORT).show();
                //方法1：打开设置界面
                activity.startActivity(new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
                        Uri.parse("package:" + activity.getPackageName())));
                return;
            }else if (Environment.isExternalStorageManager()) {
//                try {
//                    aaa(activity, curImg);
//                }catch (Exception e){
//                    Toast.makeText(activity, "请打开存储权限", Toast.LENGTH_SHORT).show();
//                }
            }
        }
    }
    public void read(View view) {
        try {
            FileInputStream fis = openFileInput("inner.txt");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            String str = new String(buffer);
            Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            Log.e("", "read: ", e);
        } catch (IOException e) {
            Log.e("", "read: ", e);
        }
    }
    public void add(View view) {
        try {
            FileOutputStream fos = openFileOutput("inner.txt", MODE_APPEND);
            fos.write("马绍鹏——文件存储".getBytes());
            fos.close();
            Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            Log.e("", "add: ", e);
        } catch (IOException e) {
            Log.e("", "add: ", e);
        }
    }
    public void outerread(View view) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File path = Environment.getExternalStorageDirectory();
            try {
                FileInputStream fis = new FileInputStream(new File(path, "outer.txt"));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                String str = new String(buffer);
                Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                Log.e("", "outerread: ", e);
            } catch (IOException e) {
                Log.e("", "outerread: ", e);
            }
        }
    }
    public void outeradd(View view) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File path = Environment.getExternalStorageDirectory();
            try {
                FileOutputStream fos = new FileOutputStream(new File(path, "outer.txt"));
                fos.write("马绍鹏——外部文件存储".getBytes());
                fos.close();
                Toast.makeText(this, "写入外部成功", Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                Log.e("", "outeradd: ", e);
            } catch (IOException e) {
                Log.e("", "outeradd: ", e);
            }
        }
    }
    public void spadd(View view) {
        try {
            SharedPreferences.Editor editor = getSharedPreferences("sp", MODE_PRIVATE).edit();
            editor.putString("name", "马绍鹏");
            editor.putInt("age", 24);
            editor.putBoolean("sex", true);
            editor.apply();
            Toast.makeText(this, "写入sp成功", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Toast.makeText(this, "写入sp失败", Toast.LENGTH_SHORT).show();
        }
    }
    public void spread(View view) {
        try {
            SharedPreferences sp = getSharedPreferences("sp", MODE_PRIVATE);
            String name = sp.getString("name", "");
            int age = sp.getInt("age", 0);
            boolean sex = sp.getBoolean("sex", false);
            Toast.makeText(this, "name:" + name + "age:" + age + "sex:" + sex, Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Toast.makeText(this, "读取sp失败", Toast.LENGTH_SHORT).show();
        }
    }

    public void dbadd(View view) {
        try {
            ContentValues values = new ContentValues();
            values.put("name", name.getText().toString());
            values.put("age", age.getText().toString());
            db.insert("user", null, values);
        }catch (Exception e){
            Toast.makeText(this, "写入数据库失败", Toast.LENGTH_SHORT).show();
        }
    }
    @SuppressLint("Range")
    public void dbread(View view) {
        try {
            @SuppressLint("Recycle") Cursor cursor = db.query("user", null, null, null, null, null, null);
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex("name"));
                int age = cursor.getInt(cursor.getColumnIndex("age"));
                Toast.makeText(this, "name:" + name + "age:" + age, Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){
            Toast.makeText(this, "读取数据库失败", Toast.LENGTH_SHORT).show();
        }
    }
    public void dbdel(View view) {
        try {

            db.delete("user", "name=?", new String[]{name.getText().toString()});
        }catch (Exception e){
            Toast.makeText(this, "删除数据库失败", Toast.LENGTH_SHORT).show();
        }
    }
    public void dbupd(View view) {
        try {
            ContentValues values = new ContentValues();
            values.put("age", age.getText().toString());
            db.update("user", values, "name=?", new String[]{name.getText().toString()});
        }catch (Exception e){
            Toast.makeText(this, "更新数据库失败", Toast.LENGTH_SHORT).show();
        }
    }
}